<template>
    <div class="online-users-container">
        <h2 class="section-title">🌟 活跃玩家大厅</h2>
        <div v-if="loading" class="status-container">
            <div class="loading-spinner"></div>
            <span class="loading-text">星空穿梭中...</span>
        </div>
        <div v-if="error" class="error-alert">⚡ {{ error }}</div>
        <div v-else class="scroll-container">
            <div class="users-grid">
                <div v-for="user in sortedOnlineUsers" :key="user.id" class="user-card">
                    <div class="avatar-wrapper">
                        <img :src="user.photo" :alt="user.username" class="user-avatar" />
                        <div class="online-pulse"></div>
                    </div>
                    <div class="user-info">
                        <span class="user-name"
                            >{{ user.username }}
                            <span v-if="user.id === userStore.id" class="current-user-badge"
                                >(我)</span
                            >
                            <el-icon v-if="isFriend(user.id)" class="friend-badge">
                                <User />
                            </el-icon>
                        </span>
                        <span class="user-id">🆔 {{ user.id }}</span>
                    </div>
                    <div class="glow"></div>

                    <!-- 新增按钮操作区 -->
                    <div class="action-buttons">
                        <button
                            v-if="user.id !== userStore.id && !isFriend(user.id)"
                            @click="handleInvite(user.id)"
                            class="invite-btn"
                            :disabled="isFriend(user.id) || isRequestSent(user.id)"
                        >
                            <el-icon>
                                <Connection />
                            </el-icon>
                            {{ isRequestSent(user.id) ? '连接中..' : '添加好友' }}
                        </button>
                        <button
                            v-if="user.id !== userStore.id"
                            @click="handleChatStart(user.id)"
                            class="chat-btn"
                        >
                            <el-icon>
                                <ChatDotRound />
                            </el-icon>
                            开始聊天
                        </button>
                    </div>
                </div>
            </div>
        </div>
        v
    </div>
</template>

<script setup>
import axios from 'axios'
import { ElMessage, ElNotification } from 'element-plus'
import { useRouter } from 'vue-router'
import { ref, onMounted, onUnmounted } from 'vue'
import { useUserStore } from '@/store/user'
import { Connection, ChatDotRound, User } from '@element-plus/icons-vue'
import { computed } from 'vue'
const onlineUsers = ref([])
let socket = null
const userStore = useUserStore()
const router = useRouter()
const loading = ref(true)
const error = ref(null)

// 新增请求状态判断
const isRequestSent = (userId) => {
    return userStore.pendingRequests.some((request) => request.fromUserId === userId)
}

const sortedOnlineUsers = computed(() => {
    return [...onlineUsers.value].sort((a) => {
        return a.id === userStore.id ? -1 : 1
    })
})

// 改为计算属性实现好友状态
const isFriend = computed(() => (userId) => {
    return userStore.friends.some((friend) => friend.id === userId)
})
// 添加事件处理方法
const handleInvite = async (fromUserId) => {
    if (isRequestSent(fromUserId)) {
        ElMessage.warning('请求已发送，请等待对方处理')
        return
    }

    try {
        await axios.post(
            'https://www.xujiaojiaojiao.cn/api/friend/request/',
            { toUserId: fromUserId },
            {
                headers: {
                    Authorization: 'Bearer ' + userStore.token,
                },
            }
        )
        // 添加请求到 store
        userStore.pendingRequests.push({
            fromUserId: fromUserId,
            timestamp: new Date().toISOString(),
        })
        ElMessage.success('好友请求已发送')
        // 显示浮动通知
        ElNotification({
            title: '请求已发送',
            message: `已向用户 ${fromUserId} 发送好友请求`,
            type: 'success',
            duration: 3000,
            offset: 60,
        })
    } catch (error) {
        ElMessage.error('发送请求失败')
    }
}

const handleChatStart = (userId) => {
    router.push({
        name: 'chat',
        params: {
            userId: userId,
        },
    })
}
onMounted(() => {
    // 建立 WebSocket 连接
    const initWebSocket = () => {
        // 确保token存在
        if (!userStore.token) {
            console.error('OnlineUsersView: WebSocket连接失败，token不存在')
            error.value = '连接失败：未登录或登录已过期'
            loading.value = false
            setTimeout(() => initWebSocket(), 2000)
            return
        }

        // 如果已有全局socket，直接使用
        if (userStore.socket) {
            console.log('OnlineUsersView: 使用已存在的WebSocket连接')
            socket = userStore.socket
            loading.value = false
            error.value = null

            // 获取当前在线用户
            onlineUsers.value = userStore.onlineUsers

            // 注册监听事件
            const originalOnMessage = socket.onmessage
            socket.onmessage = (event) => {
                try {
                    const data = JSON.parse(event.data)

                    if (data.event === 'online-users') {
                        userStore.updateOnlineUsers(data.users)
                        onlineUsers.value = userStore.onlineUsers
                        loading.value = false
                    } else if (data.event === 'friend-request') {
                        userStore.pendingRequests.push({
                            fromUserId: data.fromUserId,
                            fromUsername: data.fromUsername,
                            timestamp: new Date().toISOString(),
                        })
                        ElNotification({
                            title: '新好友请求',
                            message: `${data.fromUsername} 请求添加您为好友`,
                            duration: 5000,
                            onClick: () => router.push('/main/friends/'),
                        })
                    } else if (originalOnMessage) {
                        // 对于其他消息，传给原始处理函数
                        originalOnMessage(event)
                    }
                } catch (e) {
                    console.error('OnlineUsersView: 消息处理失败:', e)
                    error.value = '用户数据解析失败'
                    loading.value = false
                }
            }

            // 发送ping消息请求最新在线用户列表
            try {
                socket.send(JSON.stringify({ event: 'ping' }))
            } catch (e) {
                console.error('发送ping消息失败:', e)
            }
            return
        }

        // 如果没有全局socket，创建新连接
        console.log('OnlineUsersView: 创建新WebSocket连接')
        socket = new WebSocket(`wss://www.xujiaojiaojiao.cn/websocket/${userStore.token}`)
        userStore.socket = socket

        socket.onopen = () => {
            console.log('OnlineUsersView: WebSocket连接已打开')
            loading.value = false
            error.value = null

            // 发送ping消息以确保连接并请求在线用户列表
            try {
                socket.send(JSON.stringify({ event: 'ping' }))
            } catch (e) {
                console.error('发送ping消息失败:', e)
            }
        }

        socket.onmessage = (event) => {
            try {
                const data = JSON.parse(event.data)

                if (data.event === 'online-users') {
                    userStore.updateOnlineUsers(data.users)
                    onlineUsers.value = userStore.onlineUsers
                    loading.value = false
                    console.log('在线用户数据更新成功:', data.users.length)
                } else if (data.event === 'friend-request') {
                    userStore.pendingRequests.push({
                        fromUserId: data.fromUserId,
                        fromUsername: data.fromUsername,
                        timestamp: new Date().toISOString(),
                    })
                    ElNotification({
                        title: '新好友请求',
                        message: `${data.fromUsername} 请求添加您为好友`,
                        duration: 5000,
                        onClick: () => router.push('/main/friends/'),
                    })
                }
            } catch (e) {
                console.error('OnlineUsersView: 消息处理失败:', e)
                error.value = '用户数据解析失败'
                loading.value = false
            }
        }

        socket.onclose = () => {
            console.log('OnlineUsersView: WebSocket连接已关闭')
            // 尝试重新连接
            setTimeout(() => initWebSocket(), 3000)
        }
    }

    // 初始化WebSocket连接
    initWebSocket()
})

onUnmounted(() => {
    // 组件卸载时不关闭连接，因为可能其他组件还在使用
    console.log('OnlineUsersView组件卸载')
    socket = null
})
</script>

<style scoped>
.friend-badge {
    margin-left: 8px;
    color: #00ff87;
    font-size: 0.9em;
    filter: drop-shadow(0 0 5px rgba(0, 255, 135, 0.3));
}
/* 添加当前用户标识样式 */
.current-user-badge {
    color: #00ff87;
    font-size: 0.8em;
    text-shadow: 0 0 8px rgba(0, 255, 135, 0.5);
}

/* 暗夜主题容器 */
.online-users-container {
    max-width: 800px;
    margin: 2rem auto;
    padding: 2rem;
    background: #0a0a0a;
    border-radius: 16px;
    border: 1px solid rgba(255, 255, 255, 0.1);
    position: relative;
    overflow: hidden;
}

.online-users-container::before {
    content: '';
    position: absolute;
    top: -50%;
    left: -50%;
    width: 200%;
    height: 200%;
    background: linear-gradient(45deg, #7028e4 0%, #e5b2ca 50%, #7028e4 100%);
    opacity: 0.1;
    animation: bgRotate 20s linear infinite;
}

.section-title {
    color: #fff;
    font-size: 1.8rem;
    margin-bottom: 2rem;
    padding-bottom: 1rem;
    position: relative;
    text-shadow: 0 0 10px rgba(255, 255, 255, 0.3);
}

.section-title::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 2px;
    background: linear-gradient(90deg, #7028e4 0%, #e5b2ca 50%, #7028e4 100%);
}
.scroll-container {
    max-height: 500px;
    overflow-y: auto;
    padding-right: 8px;
}
/* 霓虹风格用户卡片 */
.users-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
    gap: 1.5rem;
    grid-auto-rows: minmax(160px, auto);
    padding: 10px 0;
}

.user-card {
    background: #141414;
    border-radius: 12px;
    padding: 1.5rem;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    position: relative;
    overflow: hidden;
    border: 1px solid rgba(255, 255, 255, 0.1);
}

.user-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 30px rgba(112, 40, 228, 0.3);
}

.glow {
    position: absolute;
    top: 0;
    left: -100%;
    width: 200%;
    height: 100%;
    background: linear-gradient(
        90deg,
        rgba(112, 40, 228, 0) 0%,
        rgba(112, 40, 228, 0.3) 50%,
        rgba(112, 40, 228, 0) 100%
    );
    animation: cardGlow 3s infinite;
}

/* 动态头像效果 */
.avatar-wrapper {
    position: relative;
    margin-right: 1.2rem;
}

.user-avatar {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    object-fit: cover;
    border: 2px solid #7028e4;
    box-shadow: 0 0 15px rgba(112, 40, 228, 0.3);
    transition: transform 0.3s ease;
}

.user-card:hover .user-avatar {
    transform: rotateY(360deg);
}

.online-pulse {
    position: absolute;
    bottom: 2px;
    right: 2px;
    width: 14px;
    height: 14px;
    background: #4caf50;
    border-radius: 50%;
    box-shadow: 0 0 10px #4caf50;
    animation: pulse 1.5s infinite;
}

/* 用户信息样式 */
.user-info {
    display: flex;
    flex-direction: column;
    flex: 1;
    min-width: 0; /* 防止文本溢出 */
}

.user-name {
    display: flex;
    align-items: center;
    font-weight: 600;
    color: #fff;
    letter-spacing: 0.5px;
    margin-bottom: 0.3rem;
}

.user-id {
    font-size: 0.9rem;
    color: #a0a0a0;
}

/* 加载状态特效 */
.status-container {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 3rem;
}

.loading-spinner {
    width: 30px;
    height: 30px;
    border: 3px solid rgba(112, 40, 228, 0.2);
    border-top-color: #7028e4;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-right: 1rem;
    filter: drop-shadow(0 0 5px rgba(112, 40, 228, 0.5));
}

.loading-text {
    color: #a0a0a0;
    font-size: 1.1rem;
}

/* 错误提示升级 */
.error-alert {
    background: rgba(255, 51, 51, 0.15);
    color: #ff6666;
    padding: 1.2rem;
    border-radius: 8px;
    border: 1px solid rgba(255, 102, 102, 0.3);
    backdrop-filter: blur(5px);
    text-align: center;
    margin-top: 1.5rem;
}

.action-buttons {
    margin-top: 1rem;
    display: flex;
    gap: 0.8rem;
}

.invite-btn,
.chat-btn {
    flex: 1;
    padding: 0.6rem;
    border: none;
    border-radius: 8px;
    background: rgba(112, 40, 228, 0.2);
    color: #e5b2ca;
    cursor: pointer;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 0.4rem;
}

.invite-btn:hover {
    background: #7028e4;
    color: white;
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(112, 40, 228, 0.4);
}

.chat-btn:hover {
    background: #7028e4;
    color: white;
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(76, 175, 80, 0.4);
}

.el-icon {
    font-size: 1.1rem;
}

/* 关键帧动画 */
@keyframes spin {
    to {
        transform: rotate(360deg);
    }
}

@keyframes pulse {
    0% {
        box-shadow: 0 0 0 0 rgba(76, 175, 80, 0.4);
    }
    70% {
        box-shadow: 0 0 0 10px rgba(76, 175, 80, 0);
    }
    100% {
        box-shadow: 0 0 0 0 rgba(76, 175, 80, 0);
    }
}

@keyframes cardGlow {
    0% {
        transform: translateX(-50%);
    }
    100% {
        transform: translateX(50%);
    }
}

@keyframes bgRotate {
    from {
        transform: rotate(0deg);
    }
    to {
        transform: rotate(360deg);
    }
}
</style>
